package com.cloudfun.campusshare.configuration.jpa.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author 王溪源
 * @ClassName: PropertyFilters
 * EQS_xxxx
 * @Description: TODO
 * @Date 2020/8/7 18:24
 **/
public class PropertyFilters {
    public static PropertyFilter build(String expression, String matchValue) {
        Assert.hasText (expression, "表达式不能为空");
        String restrictionNameAndClassType = StringUtils.substringBefore (expression, "_");
        String restrictionName = StringUtils.substring (restrictionNameAndClassType, 0, restrictionNameAndClassType.length () - 1);
        String classType = StringUtils.substring (restrictionNameAndClassType, restrictionNameAndClassType.length () - 1, restrictionNameAndClassType.length ());
        PropertyType propertyType = null;
        try {
            propertyType = PropertyType.valueOf (classType);
        } catch (Exception e) {

        }
        String[] propertyNames;
        if (StringUtils.contains (expression, "_OR_")) {
            String temp = StringUtils.substringAfter (expression, restrictionNameAndClassType + "_");
            propertyNames = StringUtils.splitByWholeSeparator (temp, "_OR_");
        } else {
            propertyNames = new String[1];
            propertyNames[0] = StringUtils.substringAfter (expression, "_");
        }
        return new PropertyFilter (restrictionName, propertyType, propertyNames, matchValue);
    }

    public static List<PropertyFilter> build(HttpServletRequest request) {
        return build (request, "filter");
    }

    public static List<PropertyFilter> build(HttpServletRequest request, String filterPrefix) {
        return build (request, filterPrefix, false);
    }

    public static List<PropertyFilter> build(HttpServletRequest request, boolean ignoreEmptyValue) {
        return build (request, "filter", ignoreEmptyValue);
    }

    public static List<PropertyFilter> build(HttpServletRequest request, String filterPrefix, boolean ignoreEmptyValue) {
        Map<String, Object> values = ServletUtils.getParameterStartingWith (request, filterPrefix);
        return build (values, ignoreEmptyValue);
    }

    public static List<PropertyFilter> build(Map<String, Object> filters, boolean ignoreEmptyValue) {
        List<PropertyFilter> filterList = new ArrayList<> ();
        for (Map.Entry<String, Object> entry : filters.entrySet ()) {
            String expression = entry.getKey ();
            Object value = entry.getValue ();
            if (ignoreEmptyValue && (value == null || StringUtils.isBlank (value.toString ()))) {
                continue;
            }
            PropertyFilter propertyFilter = build (expression, value.toString ());
            filterList.add (propertyFilter);
        }
        return filterList;
    }
}
